<?php

namespace app\common\service;

use app\common\model\User;
use app\common\model\WechatFans;

class UserService
{
    const TYPE_OFFICIAL_ACCOUNT = 1;    //公众号
    const TYPE_MINI_PROGRAM = 2;        //小程序
    const TYPE_PUBLIC_PLATFORM = 3;     //微信开放平台

    public static function updateFansInfo($info, $type, $appid)
    {
        switch ($type) {
            case self::TYPE_OFFICIAL_ACCOUNT:
                $data = [
                    "appid" => $appid,
                    "openid" => $info['openid'],
                    "nickname" => $info['nickname'],
                    "sex" => $info['sex'],
                    "language" => $info['language'],
                    "city" => $info['city'],
                    "province" => $info['province'],
                    "country" => $info['country'],
                    "headimgurl" => $info['headimgurl'],
                    'unionid' => isset($info['unionid']) ? $info['unionid'] : ''
                ];
                break;
            case self::TYPE_MINI_PROGRAM:
                $data = [
                    "appid" => $appid,
                    "openid" => $info['openid'],
                    "nickname" => $info['nickName'],
                    "sex" => $info['gender'],
                    "language" => $info['language'],
                    "city" => $info['city'],
                    "province" => $info['province'],
                    "country" => $info['country'],
                    "headimgurl" => $info['avatarUrl'],
                ];
                break;
            case self::TYPE_PUBLIC_PLATFORM:
                break;
        }
        $isReg = false;
        if ((new WechatFans)->get(['openid' => $info['openid'], 'appid' => $appid])) {
            WechatFans::update($data, ['openid' => $info['openid'], 'appid' => $appid]);
            $fans = (new WechatFans)->get(['openid' => $info['openid'], 'appid' => $appid]);
        } else {
            $fans = WechatFans::create($data);
            $isReg = true;
        }
        return [
            'fans' => $fans,
            'isReg' => $isReg
        ];
    }

    public static function updateUserByFans(User $user, WechatFans $fans)
    {
        if (!empty($fans['nickname'])) {
            $user['nickname'] = $fans['nickname'];
        }
        if (!empty($fans['headimgurl'])) {
            $user['avatar'] = $fans['headimgurl'];
        }
        $user['update_time'] = time();
        $user->save();
    }

}